package com.wushi.lenovo.asia5b.app_di.credit.presenter;

import android.app.Activity;
import android.text.TextUtils;

import com.mvp.base.BasePresenter;
import com.mvp.networking.CustomThrowable;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.credit.mvpview.DownPdfDFView;
import com.wushi.lenovo.asia5b.app_model.credit.BaseHisModel;
import com.wushi.lenovo.asia5b.app_utils.WFileUtil;
import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;

import javax.inject.Inject;
import javax.net.ssl.HttpsURLConnection;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static timber.log.Timber.d;

public class DownPdfDFPresenter extends BasePresenter<DownPdfDFView> {
    private final int CONNECT_TIMEOUT = 300 * 1000;//下载文件可以给5分钟

    @Inject
    public DownPdfDFPresenter() {
    }

    /**
     * 下载pdf
     *
     * @param model
     */
    public void downloadPdf(Activity mActivity, BaseHisModel model) {

        Disposable disposable2 = Observable.just(true)
                .flatMap(new Function<Boolean, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(Boolean aBoolean) throws Exception {
                        if (!aBoolean) {
                            return Observable.error(new CustomThrowable(mActivity.getString(R.string.permission_error1)));
                        }
                        if (TextUtils.isEmpty(model.getPdf_download_path()) && TextUtils.isEmpty(model.getReceipt_image_path())) {
                            return Observable.error(new CustomThrowable(mActivity.getString(R.string.addressempty)));
                        }
                        String downloadUrl = null;
                        String filePath = null;
                        if (!TextUtils.isEmpty(model.getPdf_download_path())) {//pdf地址
                            filePath = WFileUtil.createPdfPath(mActivity, model.getReference_number());
                            downloadUrl = model.getPdf_download_path();
                        } else {//图片地址
                            filePath = WFileUtil.createImagePath(mActivity, model.getReference_number());
                            downloadUrl = model.getReceipt_image_path();
                        }
                        d("--->>>>>>>>---保存地址:" + filePath);
                        InputStream inputStream = null;
                        RandomAccessFile randomAccessFile = null;
                        HttpsURLConnection connection = null;
                        try {
                            URL url = new URL(downloadUrl);
//                            connection = (HttpsURLConnection) url.openConnection();
                            connection = (HttpsURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setReadTimeout(CONNECT_TIMEOUT);
                            connection.setConnectTimeout(CONNECT_TIMEOUT);
                            connection.setRequestProperty("Accept-Encoding", "identity"); //不要使用gzip方式,添加这行代码
                            connection.connect();
                            int responseCode = connection.getResponseCode();
                            d("--->>>>>>>>---请求code:" + responseCode);

                            inputStream = connection.getInputStream();
                            int contentLength = connection.getContentLength();//文件总大小
                            randomAccessFile = new RandomAccessFile(filePath, "rwd");
                            byte[] buffer = new byte[1024 * 4];
                            int length = 0;
                            int xiazaiLength = 0;
                            while ((length = inputStream.read(buffer)) != -1) {
                                randomAccessFile.write(buffer, 0, length);
                                xiazaiLength += length;
                                d("--->>>>>>>>---" + String.format("xiazaiLength:%d,contentLength:%d", xiazaiLength, contentLength));
                            }
                        } catch (Exception e) {
                            Observable.error(e.getCause());
                        }
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (connection != null) {
                            connection.disconnect();
                        }
                        if (randomAccessFile != null) {
                            try {
                                randomAccessFile.close();
                            } catch (IOException e) {
                                Observable.error(e.getCause());
                            }
                        }
                        return Observable.just(filePath);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    showLoadingBar(mActivity.getString(R.string.downloading));
                })
                .doAfterTerminate(() -> {
                    dismissLoadingBar("all");
                })
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String filePath) throws Exception {
                        getView().downloadPdfResult(model, filePath);
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    CrashHelper.postCatchedException(throwable);
                    if (throwable instanceof CustomThrowable) {
                        ToastUtil.showToast(throwable.getMessage());
                    }
                });
        composite.add(disposable2);

    }
}
